package com.interest.controller.api;

import com.alibaba.fastjson.JSONObject;
import com.interest.authorization.manager.impl.RedisTokenManager;
import com.interest.base.entity.ModelBean;
import com.interest.base.utils.TokenUtils;
import com.interest.modules.account.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created by wangliang on 16-11-2.
 */
@Controller
@RequestMapping("/api/reg")
public class ApiRegController {
    @Autowired
    private AccountService accountService;

    @Autowired
    private RedisTokenManager redisTokenManager;

    @RequestMapping(method = RequestMethod.POST)
    @ResponseBody
    public ModelBean reg(@RequestParam(value = "username") String username,
                         @RequestParam(value = "password") String password,
                         @RequestParam(value = "rpassword") String rpassword) {
        if (username == null || "".equals(username)) {
            return new ModelBean("用户名不能为空");
        } else if (password == null || password.length() < 6) {
            return new ModelBean("密码格式不对");
        } else if (!password.equals(rpassword)) {
            return new ModelBean("两次输入的密码不相同");
        } else {
            int ret = accountService.regAccount(username, password);
            if (ret == 0) {
                String token = TokenUtils.generateToken();
                redisTokenManager.createRelationship(username, token);
                JSONObject data = new JSONObject();
                data.put("username", username);
                data.put("token", token);
                return new ModelBean(data);
            } else {
                return new ModelBean("该账号已经被注册");
            }
        }

    }
}
